package cn.sinokj.party.chineseFourParty.activity;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Message;
import android.support.v4.app.FragmentTransaction;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.gyf.barlibrary.ImmersionBar;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.sinokj.party.chineseFourParty.R;
import cn.sinokj.party.chineseFourParty.activity.base.BaseActivity;
import cn.sinokj.party.chineseFourParty.app.App;
import cn.sinokj.party.chineseFourParty.fragment.HomeFragment;
import cn.sinokj.party.chineseFourParty.fragment.MainNewsFragment;
import cn.sinokj.party.chineseFourParty.fragment.LoginFragment;
import cn.sinokj.party.chineseFourParty.fragment.MineFragment;
import cn.sinokj.party.chineseFourParty.fragment.AboutAsFragment;
import cn.sinokj.party.chineseFourParty.service.HttpDataService;
import cn.sinokj.party.chineseFourParty.utils.Constans;
import cn.sinokj.party.chineseFourParty.utils.SoftKeyboardUtil;
import cn.sinokj.party.chineseFourParty.view.dialog.confirm.ConfirmDialog;
import cn.sinokj.party.chineseFourParty.view.dialog.confirm.ConfirmInterface;
import de.greenrobot.event.EventBus;
import de.greenrobot.event.Subscribe;
import de.greenrobot.event.ThreadMode;
import me.iwf.photopicker.PhotoPicker;
import pub.devrel.easypermissions.EasyPermissions;


/**
 * 首页注释
 */
public class MainActivity extends BaseActivity implements EasyPermissions.PermissionCallbacks {
    private static final int HOMENUM = 1;
    private static final int INTERACTNUM = 2;
    private static final int ABOUTUSNUM = 3;
    private static final int MINENUM = 4;
    private static final int LOGINNUM = 5;
    private static final int STARTIMAGENAME = 102;
    @BindView(R.id.main_framelayout)
    FrameLayout mainFramelayout;
    @BindView(R.id.bottom_home_image)
    ImageView bottomHomeImage;
    @BindView(R.id.bottom_home_text)
    TextView bottomHomeText;
    @BindView(R.id.bottom_home_layout)
    RelativeLayout bottomHomeLayout;
    @BindView(R.id.bottom_news_text)
    TextView bottomInteractText;
    @BindView(R.id.bottom_news_layout)
    RelativeLayout bottomInteractLayout;
    @BindView(R.id.bottom_interaction_text)
    TextView bottomStageText;
    @BindView(R.id.bottom_aboutus_layout)
    RelativeLayout bottomStageLayout;
    @BindView(R.id.bottom_mine_text)
    TextView bottomMineText;
    @BindView(R.id.bottom_mine_layout)
    RelativeLayout bottomMineLayout;
    @BindView(R.id.main_bottombar)
    LinearLayout mainBottombar;

    private HomeFragment mHomeFragment;
    private MainNewsFragment mInteractFragment;
    private AboutAsFragment mAboutAsFragment;
    private MineFragment mMineFragment;
    private LoginFragment mLoginFragment;
    //沉浸式状态栏
    public ImmersionBar mImmersionBar;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Glide.with(this).load("df").into(500,500);
        ButterKnife.bind(this);
        EventBus.getDefault().register(this);
        //沉浸式状态栏的初始化
        mImmersionBar = ImmersionBar.with(this);
        mImmersionBar.init();
        showFragment(HOMENUM);
        requestPermissions();
        initializeBottom(R.id.bottom_home_layout);
        //解决底部导航栏顶出问题
        SoftKeyboardUtil.observeSoftKeyboard(MainActivity.this, new SoftKeyboardUtil
                .OnSoftKeyboardChangeListener() {
            @Override
            public void onSoftKeyBoardChange(int softKeybardHeight, boolean visible) {
                if (visible) {
                    if (mainBottombar.getVisibility() == View.VISIBLE) {
                        mainBottombar.setVisibility(View.GONE);
                    }
                } else {
                    if (mainBottombar.getVisibility() == View.GONE) {
                        mainBottombar.setVisibility(View.VISIBLE);
                    }
                }
            }
        });

        String vcRes = App.loginInfo.getVcRes();
        if(!TextUtils.isEmpty(vcRes)){
            ConfirmDialog.confirmAction(this, vcRes, "确定", null, null);
        }
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        String vcRes = App.loginInfo.getVcRes();
        if(!TextUtils.isEmpty(vcRes)){
            ConfirmDialog.confirmAction(this, vcRes, "确定", null, null);
        }
    }

    @Override
    protected Map<String, JSONObject> getDataFunction(int what, int arg1, int arg2, Object obj) {
        switch (what) {
            case STARTIMAGENAME:
                return HttpDataService.startphoto();
        }
        return null;
    }

    @Override
    protected void httpHandlerResultData(Message msg, JSONObject jsonObject) {
        switch (msg.what) {
            case STARTIMAGENAME:
                String vcIcon = jsonObject.opt("vcIcon").toString();
                String startImgURL = preferencesUtil.getString("startImgURL");
                if(!TextUtils.equals(vcIcon,startImgURL)){
                    preferencesUtil.putString("startImgURL",vcIcon);
                }
                break;
        }

    }

    /**
     * 显示相对应的Fragment
     *
     * @param Index
     */
    private void showFragment(int Index) {
        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
        hideFragment(transaction);
        switch (Index) {
            case HOMENUM:
                initializeBottom(R.id.bottom_home_layout);
                if (mHomeFragment == null) {
                    mHomeFragment = new HomeFragment();
                    transaction.add(R.id.main_framelayout, mHomeFragment);
                } else {
                    transaction.show(mHomeFragment);
                }
                break;
            case INTERACTNUM:
                initializeBottom(R.id.bottom_news_layout);
                if (mInteractFragment == null) {
                    mInteractFragment = new MainNewsFragment();
                    transaction.add(R.id.main_framelayout, mInteractFragment);
                } else {
                    transaction.show(mInteractFragment);
                }
                break;
            case ABOUTUSNUM:
                initializeBottom(R.id.bottom_aboutus_layout);
                if (mAboutAsFragment == null) {
                    mAboutAsFragment = new AboutAsFragment();
                    transaction.add(R.id.main_framelayout, mAboutAsFragment);
                } else {
                    transaction.show(mAboutAsFragment);
                }
                break;
            case MINENUM:
                initializeBottom(R.id.bottom_mine_layout);
                if (mMineFragment == null) {
                    mMineFragment = new MineFragment();
                    transaction.add(R.id.main_framelayout, mMineFragment);
                } else {
                    transaction.show(mMineFragment);
                }
                break;
            case LOGINNUM:
                if (mLoginFragment == null) {
                    mLoginFragment = new LoginFragment();
                    transaction.add(R.id.main_framelayout, mLoginFragment);
                } else {
                    transaction.show(mLoginFragment);
                }
                break;
        }
        transaction.commitAllowingStateLoss();
    }

    /**
     * 点击监听事件
     *
     * @param view
     */
    @OnClick({R.id.bottom_home_layout, R.id.bottom_news_layout, R.id.bottom_aboutus_layout, R.id
            .bottom_mine_layout})
    public void OnClick(View view) {
        switch (view.getId()) {
            case R.id.bottom_home_layout:
                showFragment(HOMENUM);
                break;
            case R.id.bottom_news_layout:
                showFragment(INTERACTNUM);
                break;
            case R.id.bottom_aboutus_layout:
                //if (App.loginStatus) {
                    showFragment(ABOUTUSNUM);
               // } else {
                //  startActivity(new Intent(this,LoginInActivity.class));
               // }
                break;
            case R.id.bottom_mine_layout:
                if (App.loginStatus) {
                    showFragment(MINENUM);
                } else {
                    startActivity(new Intent(this,LoginInActivity.class));
                }

                break;
        }
    }

    @Subscribe(threadMode = ThreadMode.MainThread)
    public void onEvent(Message msg) {
        switch (msg.what) {
            case Constans.SHOW_MINE:
                showFragment(MINENUM);
                break;
            case Constans.SHOW_HOME:
                showFragment(HOMENUM);
                break;
            case Constans.SHOW_LOGIN:
                showFragment(LOGINNUM);
                break;
        }
    }

    /**
     * 选中状态的切换
     *
     * @param resourceId
     */
    protected final void initializeBottom(int resourceId) {
        int[][] resourceIds = {
                {R.id.bottom_home_layout, R.id.bottom_home_text, R.id.bottom_home_image, R.drawable
                        .icon_homepage_nor, R.drawable.icon_homepage_pre},
                {R.id.bottom_news_layout, R.id.bottom_news_text, R.id.bottom_news_image, R
                        .drawable.icon_notice_nor, R.drawable.icon_notice_pre},
                {R.id.bottom_aboutus_layout, R.id.bottom_interaction_text, R.id.bottom_interaction_image, R.drawable
                        .icon_aboutus_nor, R.drawable.icon_aboutus_pre},
                {R.id.bottom_mine_layout, R.id.bottom_mine_text, R.id.bottom_mine_image, R.drawable
                        .icon_mine_nor, R.drawable.icon_mine_pre},
        };
        for (int i = 0; i < 4; i++) {
            RelativeLayout layout = (RelativeLayout) findViewById(resourceIds[i][0]);
            TextView textView = (TextView) findViewById(resourceIds[i][1]);
            ImageView imageView = (ImageView) findViewById(resourceIds[i][2]);
            imageView.setImageResource(resourceIds[i][3]);
            textView.setTextColor(getResources().getColor(R.color.gray));
            if (resourceId == resourceIds[i][0]) {
                imageView.setImageResource(resourceIds[i][4]);
                textView.setTextColor(getResources().getColor(R.color.colorPrimary));
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
        if (mImmersionBar != null) {
            mImmersionBar.destroy();  //在BaseActivity里销毁
        }
    }

    /**
     * 隐藏所有Fragment
     *
     * @param transaction
     */
    private void hideFragment(FragmentTransaction transaction) {
        if (mHomeFragment != null) {
            transaction.hide(mHomeFragment);
        }
        if (mInteractFragment != null) {
            transaction.hide(mInteractFragment);
        }
        if (mAboutAsFragment != null) {
            transaction.hide(mAboutAsFragment);
        }
        if (mMineFragment != null) {
            transaction.hide(mMineFragment);
        }
        if (mLoginFragment != null) {
            transaction.hide(mLoginFragment);
        }
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK && requestCode == PhotoPicker.REQUEST_CODE) {
            if (data != null) {
                ArrayList<String> photos =
                        data.getStringArrayListExtra(PhotoPicker.KEY_SELECTED_PHOTOS);
                String picPath = photos.get(0);
                if (mMineFragment != null) {
                    mMineFragment.setHeadImage(picPath);
                    mMineFragment.upLoadImage();
                }
            }
        }

    }

    @Override
    public void onBackPressed() {
        confirmAction("确定要退出吗？", "确定", "取消", new ConfirmInterface() {
            @Override
            public void onOkButton() {
                System.exit(0);
            }

            @Override
            public void onCancelButton() {

            }

            @Override
            public void onDismiss(DialogInterface dialog) {

            }
        });
    }


    private AlertDialog confirmDialog;

    protected final void confirmAction(String message, String okString, String cancelString,
                                       ConfirmInterface confirmIf) {
        confirmDialog = new AlertDialog.Builder(this, R.style.dialog_round).create();
        confirmDialog.setOnKeyListener(new DialogInterface.OnKeyListener() {
            @Override
            public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
                if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {
                    confirmDialog.dismiss();
                }
                return false;
            }
        });
        final ConfirmInterface confirmInterface = confirmIf;
        confirmDialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
            @Override
            public void onDismiss(DialogInterface dialog) {
                if (confirmInterface != null) {
                    confirmInterface.onDismiss(dialog);
                }
            }
        });
        confirmDialog.setCancelable(true);
        confirmDialog.show();
        confirmDialog.setContentView(R.layout.finish_dialog);
        TextView confirm = (TextView) confirmDialog.findViewById(R.id.confirm_message);
        TextView cancel = (TextView) confirmDialog.findViewById(R.id.cancel_bady);
        TextView ok = (TextView) confirmDialog.findViewById(R.id.ok_bady);
        if (!TextUtils.isEmpty(message)) {
            confirm.setText(message);
        }
        if (!TextUtils.isEmpty(okString)) {
            ok.setText(okString);
        } else {
            ok.setVisibility(View.GONE);
        }
        if (!TextUtils.isEmpty(cancelString)) {
            cancel.setText(cancelString);
        } else {
            cancel.setVisibility(View.GONE);
        }

        cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (confirmInterface != null) {
                    confirmInterface.onCancelButton();
                }
                confirmDialog.dismiss();
            }
        });
        ok.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (confirmInterface != null) {
                    confirmInterface.onOkButton();
                }
                confirmDialog.dismiss();
            }
        });
    }


    private void requestPermissions() {
        String[] perms = {
                android.Manifest.permission.WRITE_EXTERNAL_STORAGE,
                android.Manifest.permission.READ_EXTERNAL_STORAGE
        };

        if (EasyPermissions.hasPermissions(this, perms)) {

        } else {
            EasyPermissions.requestPermissions(this, "请求获取SD权限", Constans.GET_LOCATION_PERMISSION, perms);
        }
    }

    @Override
    public void onPermissionsGranted(int requestCode, List<String> perms) {

    }

    @Override
    public void onPermissionsDenied(int requestCode, List<String> perms) {

    }
}
